package com.king.base.service.user.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.king.base.auth.security.JwtUser;
import com.king.base.auth.utils.EncryptUtils;
import com.king.base.domain.role.Role;
import com.king.base.domain.user.UserRole;
import com.king.base.exception.BadRequestException;
import com.king.base.exception.EntityExistException;
import com.king.base.exception.EntityNotFoundException;
import com.king.base.auth.utils.EntityUtils;
import com.king.base.mapper.role.RoleMapper;
import com.king.base.service.user.UserRoleService;
import com.king.base.utils.ValidationUtil;
import com.king.base.domain.user.User;
import com.king.base.mapper.user.UserMapper;
import com.king.base.service.user.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author TianYZ
 * @date 2019-06-16
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {
    @Autowired
    private UserRoleService userRoleService;
    @Resource
    private RoleMapper roleMapper;
    @Override
    public User findByUserId(String userId) {
        User user=baseMapper.findByUserId(userId);
        return user;
    }

    @Override
    public IPage<User> page(Pageable pageable, User user) {
        Page<User> page=new Page<User>(pageable.getPageNumber(),pageable.getPageSize());
        List<User> userList=baseMapper.page(page,user);
        return page.setRecords(userList);
    }

    @Override
    public boolean saveOrUpdate(User user) {
        if(baseMapper.checkLoginNameUnique(user)>0){
            throw new EntityExistException(User.class,"登录名",user.getLoginName());
        }
        if(user.getRoleIds() == null || user.getRoleIds().length == 0){
            throw new BadRequestException("角色不能为空");
        }
        User entity=baseMapper.findByEmail(user.getEmail());
        if(entity!=null &&
                (StringUtils.isEmpty(user.getUserId())
                        || StringUtils.isNotBlank(user.getUserId()) &&!entity.getUserId().equals(user.getUserId())) ){
            throw new EntityExistException(User.class,"邮箱",user.getEmail());
        }
        if(StringUtils.isEmpty(user.getAvatar())){
            user.setAvatar("https://i.loli.net/2018/12/06/5c08894d8de21.jpg");
        }
        if(StringUtils.isNotBlank(user.getPassword())){
            user.setPassword(EncryptUtils.encryptPassword(user.getPassword()));
        }else{
            user.setPassword(EncryptUtils.encryptPassword("123456"));
        }
        if(StringUtils.isNotBlank(user.getUserId())){
            EntityUtils.setUpdatedInfo(user);
        }else{
            EntityUtils.setCreateAndUpdateInfo(user);
        }
        if(super.saveOrUpdate(user)){
            //删除用户所有角色
            userRoleService.deleteUserRole(user.getUserId(),null);
            List<UserRole> list=new ArrayList<>();
            for(String s:user.getRoleIds()){
                UserRole userRole=new UserRole(user.getUserId(),s);
                list.add(userRole);
            }
            userRoleService.saveBatch(list);
            return true;
        }else{
            return false;
        }
    }
    @Override
    public void delete(String userId) {
        //根据实际情况修改
        if(userId.equals("1")){
            throw new BadRequestException("该账号不能被删除");
        }
        userRoleService.deleteUserRole(userId,null);
        baseMapper.deleteById(userId);
    }

    @Override
    public User findByName(String loginName) {
        User user = null;
        if(ValidationUtil.isEmail(loginName)){
            user = baseMapper.findByEmail(loginName);
        } else {
            user = baseMapper.findByLoginName(loginName);
        }
        if (user == null) {
            throw new EntityNotFoundException(User.class, "loginName", loginName);
        }else{
            List<Role> roles=roleMapper.findByUserId(user.getUserId());
            user.setRoles(roles);
        }
        return user;
    }

    @Override
    public void updatePass(JwtUser jwtUser, String pass) {
        baseMapper.updatePass(jwtUser.getUserId(),pass);
    }

    @Override
    public void updateAvatar(JwtUser jwtUser, String url) {
        baseMapper.updateAvatar(jwtUser.getUserId(),url);
    }

    @Override
    public void updateEmail(JwtUser jwtUser, String email) {
        baseMapper.updateEmail(jwtUser.getUserId(),email);
    }

    @Override
    public void updateUserStatus(User user) {
        super.updateById(user);
    }
}
